<?php

namespace app\api\controller;

use addons\third\library\Service;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Sms;
use app\common\validate\UserValidate;
use fast\Http;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'login_wx', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }



    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $password 密码
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $password = $this->request->request('password');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');


        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($mobile, $password, '', $mobile, [
            'is_yewuyuan' => 1
        ]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        (new UserValidate())->goCheck();
        $user = $this->auth->getUser();
        $param = $this->request->param();
        $param['id'] = UID;

        $user->allowField(['avatar', 'nickname', 'mobile', 'real_name', 'profession'])
        ->data($param)->save();

        $this->success('保存成功');
    }




    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $mobile = $this->request->request("mobile");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByUsername($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //===================================
    /**
     * 小程序登录
     */
    public function login_wx()
    {
        $config = config('site.wxapp');

        $code = $this->request->post("code", '');
        $rawData = $this->request->post("rawData", '', 'trim');
        $parent_id = input('parent_id/d', 0);
        if (!$code || !$rawData) {
            $this->error("参数不正确");
        }
        $userInfo = (array)json_decode($rawData, true);
        $params = [
            'appid'      => $config['wxappid'],
            'secret'     => $config['wxappsecret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => $userInfo['nickName'],
                    ],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                $extend = ['parent_id'=> $parent_id, 'gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
                $ret = Service::connect($platform, $result, $extend, 10*24*3600);
                if ($ret) {
                    $auth = Auth::instance();
                    $this->success("登录成功", ['userInfo' => $auth->getUserinfo()]);
                } else {
                    $this->error("连接失败");
                }
            }
        }

        $this->error('登陆失败');

    }

    public function getUserInfo() {
        $userinfo = $this->auth->getUserinfo();

        $this->success('userinfo', $userinfo);
    }

    //获取未读消息数量
    public function getNoReadNum() {
        $db = Db::name('custom_info');
        $where['user_id']  = ['in', [0, UID]];
        $count = $db->where($where)->where('id', 'not in', function($query) {
            $query->name('custom_info_read')->where(['user_id' => UID])->field('info_id');
        })->count();

        $this->success('未阅读消息', $count ?? 0);
    }

    //进入之后 把阅读历史写入
    public function addRead() {
        $db = Db::name('custom_info');
        $where['user_id']  = ['in', [0, UID]];

        //ids 未读的
        $ids = $db->where($where)->where('id', 'not in', function($query) {
            $query->name('custom_info_read')->where(['user_id' => UID])->field('info_id');
        })->column('id');

        $all = [];
        foreach ($ids as $v) {
            $temp = [
                'user_id' => UID,
                'info_id' => $v,
                'createtime' => time()
            ];

            array_push($all, $temp);
        }

        $db->name('custom_info_read')->insertAll($all);

        $this->success('添加成功');
    }
}
